package com.arunsawad.ilertu.activity;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Utils;
import com.arunsawad.ilertu.common.Validator;

public class ChangePassword extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	AlertDialog.Builder alertDialogBuilder;
	AlertDialog alert;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_changepassword);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title0_imgbtn_txt);
		
		initTitle();
		
		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);
		Validator.Validate(this, preferences);
	}
	
	public void initTitle(){
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title0_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});
		
		TextView txtTitle = (TextView) findViewById(R.id.title0_txtTitle);
		txtTitle.setText(getString(R.string.change_password));
	}

	// {{ onClick events
	public void changePassword(View view) {
		String current = ((EditText) findViewById(R.id.changepassword_txtCurrent))
				.getText().toString();
		String newPass = ((EditText) findViewById(R.id.changepassword_txtNew))
				.getText().toString();
		String confirm = ((EditText) findViewById(R.id.changepassword_txtConfirm))
				.getText().toString();
		if (!newPass.equals(confirm)) {
			Utils.alert(ChangePassword.this,
					getString(R.string.confirm_password_mismatched));
		} else {
			String filter = "";
			filter += "	<user id=\""
					+ preferences.getString(Constants.PREF_USER_ID, "") + "\">";
			filter += "		<changedPassword>";
			filter += "			<newPassword>" + newPass + "</newPassword>";
			filter += "			<oldPassword>" + current + "</oldPassword>";
			filter += "		</changedPassword>";
			filter += "	</user>";

			String msg = String.format(Constants.MSG,
					"ilertu.user-password-change",
					preferences.getString(Constants.PREF_USER_NAME, ""),
					preferences.getString(Constants.PREF_PASSWORD, ""),
					preferences.getString(Constants.PREF_LANGUAGE, "en"),
					filter);

			RequestTask task = new RequestTask();
			task.setListener(this);
			task.execute(Constants.URL_UPDATE_PASSWORD, msg);
		}
	}

	// }}

	// {{ callback
	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));

				NodeList listOfItems = document.getElementsByTagName("error");
				int totalElements = listOfItems.getLength();

				if (totalElements > 0) {
					Element error = (Element) listOfItems.item(0);
					String message = error.getElementsByTagName("errorDesc")
							.item(0).getTextContent();
					Utils.alert(this, message);
				} else {
					listOfItems = document.getElementsByTagName("user");
					totalElements = listOfItems.getLength();
					if (totalElements > 0) {
						Element user = (Element) listOfItems.item(0);
						String password = user.getElementsByTagName("password")
								.item(0).getTextContent();
						SharedPreferences.Editor editor = getSharedPreferences(
								Constants.PREF_FILE, MODE_PRIVATE).edit();
						editor.putString(Constants.PREF_PASSWORD, password);
						editor.commit();

						alertDialogBuilder = new AlertDialog.Builder(this);
						alertDialogBuilder
								.setMessage(R.string.password_changed)
								.setCancelable(false)
								.setPositiveButton(R.string.ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												Intent intent = new Intent(
														ChangePassword.this,
														Home.class);
												startActivity(intent);
											}
										});
						alert = alertDialogBuilder.create();
						alert.show();
					} else {
						Utils.alert(this, getString(R.string.error_occurred));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	// }}
}
